package com.yeskery.nut.extend.jdbc;

import com.yeskery.nut.util.JdbcUtils;
import com.yeskery.nut.util.cache.ConnectionCreator;
import com.yeskery.nut.util.cache.ConnectionPoolCache;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

/**
 * 构建基础的缓存数据源
 * @author sprout
 * 2022-06-02 17:50
 */
public class WrapCacheDataSource extends ConnectionPoolCache<Connection> implements DataSource {


    /**
     * 构建基础的不支持连接池数据源
     * @param connectionCreator 连接创建器
     * @param maxConnectionSize 最大连接数
     * @param maxWaitTimeout 最大等待毫秒数
     */
    public WrapCacheDataSource(ConnectionCreator<Connection> connectionCreator, int maxConnectionSize, int maxWaitTimeout) {
        super(connectionCreator, maxConnectionSize, maxConnectionSize);
    }

    /**
     * 构建基础的不支持连接池数据源
     * @param connectionCreator 连接创建器
     * @param maxConnectionSize 最大连接数
     */
    public WrapCacheDataSource(ConnectionCreator<Connection> connectionCreator, int maxConnectionSize) {
        super(connectionCreator, maxConnectionSize);
    }

    @Override
    protected void closeConnection(Connection connection) {
        JdbcUtils.closeConnection(connection);
    }

    @Override
    protected boolean isConnectionClosed(Connection connection) {
        try {
            return connection.isClosed();
        } catch (SQLException e) {
            throw new DataAccessException("Connection Execute Fail.", e);
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
        return getCacheConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        throw new SQLException("Unsupported Operation.");
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        throw new SQLException("Unsupported Operation.");
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        throw new SQLException("Unsupported Operation.");
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        throw new SQLException("Unsupported Operation.");
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        throw new SQLException("Unsupported Operation.");
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        throw new SQLException("Unsupported Operation.");
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        throw new SQLException("Unsupported Operation.");
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException("Unsupported Operation.");
    }
}
